<template>
  <div class="login" @click="optionsShow = false">
    <div class="login-content">
      <div class="lg-lang">
        <div class="select" @click.stop="optionsShow = !optionsShow">
          <i class="iconfont icon-guojihua"></i>
          {{ lang }}
          <i class="el-icon-arrow-down"></i>
        </div>
      </div>
      <div class="selectOption" v-show="optionsShow">
        <div
          @click="changeLang(ilang)"
          :class="['ilang', ilang === lang ? 'active' : '']"
          v-for="ilang in langs"
          :key="ilang"
        >
          {{ ilang }}
        </div>
      </div>
      <div class="logo">
        <img src="@/assets/images/logo.png" alt="logo" width="50" height="50" />
      </div>
      <div class="selectLogin">
        <span
          :class="['loginOp', login === option ? 'active' : '']"
          v-for="option in loginOption"
          :key="option"
          @click="login = option"
          >{{ option }}</span
        >
      </div>
      <div class="inputs">
        <div
          class="select"
          v-if="login === '外部组织登录' || login === 'External Login'"
        >
          <div>{{ inputsVal[0].label }}</div>
          <el-select
            v-model="form.outOrg"
            :placeholder="inputsVal[0].placeholder"
            clearable
            size="small"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="input">
          <div>{{ inputsVal[1].label }}</div>
          <input
            type="text"
            v-model="form.username"
            :placeholder="inputsVal[1].placeholder"
            @keydown.enter="handleLogin"
          />
        </div>
        <div class="input">
          <div>{{ inputsVal[2].label }}</div>
          <input
            type="password"
            v-model="form.password"
            :placeholder="inputsVal[2].placeholder"
            @keydown.enter="handleLogin"
          />
        </div>
        <div class="input canvas" v-if="ifShowCanvas">
          <div>验证：</div>
          <input
            style="width: 200px"
            type="text"
            placeholder="请输入验证码"
            class="input-val"
            v-model.trim="yanzhen"
          />
          <canvas id="canvas" width="130px" height="33px" @click="handleCanvas">
          </canvas>
        </div>
        <div class="remember">
          <el-checkbox
            :label="rememberInfo"
            name="type"
            v-model="form.remember"
          ></el-checkbox>
        </div>
        <el-button @click="handleLogin" type="primary">{{
          loginInfo
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getIfNeedCode, login as loginFn } from "@/http/api";
import { Base64 } from "js-base64";
export default {
  name: "login",
  data() {
    return {
      lang: "中文",
      langs: ["中文", "English"],
      loginOption: ["内部组织登录", "外部组织登录"],
      login: "内部组织登录",
      inputsVal: [
        {
          label: "外部组织",
          placeholder: "请选择外部组织",
        },
        {
          label: "账号",
          placeholder: "请输入账号",
        },
        {
          label: "密码",
          placeholder: "请输入密码",
        },
      ],
      rememberInfo: "记住账号",
      loginInfo: "登录",
      optionsShow: false,
      form: {
        username: "",
        password: "",
        remember: false,
        outOrg: "",
      },
      // *** 返回外部组织列表 ***
      options: [
        {
          label: "test",
          value: "test",
        },
      ],
      ifShowCanvas: false,
      yanzhen: "", //输入框双向绑定的值
      true_code: "", //保存正确的验证码
      yanzhen_arr: [],
    };
  },
  async mounted() {
    let username = localStorage.getItem("username");
    if (username) {
      this.form.username = username;
      this.form.password = Base64.decode(localStorage.getItem("password"));
      this.form.remember = true;
    }
    await this.getIfNeedCanvas(0);
    if (this.ifShowCanvas) {
      this.draw(this.yanzhen_arr);
    }
  },
  methods: {
    changeLang(ilang) {
      if (this.lang !== ilang) {
        if (ilang === "中文") {
          this.loginOption = ["内部组织登录", "外部组织登录"];
          this.login = "内部组织登录";
          this.inputsVal = [
            {
              label: "外部组织",
              placeholder: "请选择外部组织",
            },
            {
              label: "账号",
              placeholder: "请输入账号",
            },
            {
              label: "密码",
              placeholder: "请输入密码",
            },
          ];
          this.rememberInfo = "记住账号";
          this.loginInfo = "登录";
          document.title = "云桌-综合办公系统";
        } else if (ilang === "English") {
          this.loginOption = ["Internal Login", "External Login"];
          (this.login = "Internal Login"),
            (this.inputsVal = [
              {
                label: "External organizations",
                placeholder: "Please select an external organization",
              },
              {
                label: "Account number",
                placeholder: "Please enter account",
              },
              {
                label: "Password",
                placeholder: "Please enter the password",
              },
            ]);
          this.rememberInfo = "Remember the account number";
          this.loginInfo = "Log in";
          document.title = "cloudTable-OA";
        }
        this.lang = ilang;
      }
    },
    async handleLogin() {
      if (
        this.form.username.trim() === "" ||
        this.form.password.trim() === ""
      ) {
        this.$message({
          message: "账号或密码不能为空",
          type: "error",
        });
        return;
      }
      if (this.ifShowCanvas) {
        if (this.yanzhen.trim()) {
          if (this.yanzhen.trim().toLowerCase() !== this.true_code) {
            this.$message({
              message: "验证码错误",
              type: "error",
            });
            this.handleCanvas();
            return;
          }
        } else {
          this.$message({
            message: "清填写验证码",
            type: "error",
          });
          return;
        }
      }
      if (this.login === "外部组织登录" || this.login === "External Login") {
        if (this.form.outOrg === "") {
          this.$message({
            message: "外部组织不能为空",
            type: "error",
          });
        }
      }
      let res = await loginFn(this.form);
      if (res.code !== 20041) {
        this.$message({
          type: "error",
          message: res.msg,
        });
      } else {
        localStorage.setItem("userInfo", JSON.stringify(res.data.employee));
        localStorage.setItem("cookie", JSON.stringify(res.data.token));
        if (this.form.remember) {
          localStorage.setItem("username", this.form.username);
          localStorage.setItem("password", Base64.encode(this.form.password));
        }
        window.location.href = window.origin + "/#/proportal/index";
        window.location.reload()
      }
    },
    async getIfNeedCanvas(tenant_id) {
      let res = await getIfNeedCode(tenant_id);
      if (res.code === 20041 && res.data) {
        this.ifShowCanvas = true;
      }
    },
    draw(show_num) {
      var canvas_width = document.querySelector("#canvas").clientWidth;
      var canvas_height = document.querySelector("#canvas").clientHeight;
      var canvas = document.getElementById("canvas"); //获取到canvas
      var context = canvas.getContext("2d"); //获取到canvas画图
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      var sCode =
        "a,b,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      var aCode = sCode.split(",");
      var aLength = aCode.length; //获取到数组的长度

      //4个验证码数
      for (var i = 0; i <= 3; i++) {
        var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        var deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        var txt = aCode[j]; //得到随机的一个内容
        show_num[i] = txt.toLowerCase(); // 依次把取得的内容放到数组里面
        var x = 10 + i * 20; //文字在canvas上的x坐标
        var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      //验证码上显示6条线条
      for (var i = 0; i <= 5; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.stroke();
      }
      //验证码上显示31个小点
      for (var i = 0; i <= 30; i++) {
        context.strokeStyle = this.randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }

      //最后把取得的验证码数组存起来，方式不唯一
      var num = show_num.join("");
      // console.log(num);
      this.true_code = num;
    },
    //得到随机的颜色值
    randomColor() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },
    //canvas点击刷新
    handleCanvas() {
      this.draw(this.yanzhen_arr);
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f1f3f6;
  width: 100vw;
  height: 100vh;
  box-shadow: 0 4px 14px rgb(197 206 227 / 25%);
  .login-content {
    width: 100%;
    height: 100%;
    max-height: 556px;
    max-width: 458px;
    background-color: #fff;
    border-radius: 10px;
    position: relative;
    .lg-lang {
      padding-top: 40px;
      padding-right: 50px;
      font-size: 12px;
      color: #646a73;
      display: flex;
      justify-content: flex-end;
      .select {
        cursor: pointer;
        i {
          font-size: 12px;
        }
      }
    }
    .selectOption {
      position: absolute;
      top: 70px;
      right: 50px;
      box-shadow: 0 4px 20px rgb(106 114 146 / 20%);
      .ilang {
        cursor: pointer;
        width: 116px;
        padding: 0 18px;
        line-height: 32px;
        font-size: 14px;
        border-left: 2px solid transparent;
        &:hover {
          background-color: #f5f7f7;
        }
        &.active {
          border-left: 2px solid #4c78fc;
        }
      }
    }
    .logo {
      display: flex;
      justify-content: center;
      margin: 0 auto;
      padding: 20px 0 20px;
    }
    .selectLogin {
      display: flex;
      justify-content: space-around;
      width: 100%;
      .loginOp {
        color: #646a73;
        font-size: 20px;
        cursor: pointer;
        &.active {
          color: #000;
          transform: scale(1.1);
          position: relative;
          &::after {
            content: " ";
            width: 30px;
            height: 4px;
            border-radius: 5px;
            background-color: #4c78fc;
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
          }
        }
      }
    }
    .inputs {
      padding: 40px 64px 0;
      .input {
        padding-bottom: 20px;
        &.canvas {
          input {
            width: 200px;
          }
          canvas {
            position: absolute;
          }
        }
        input {
          width: 100%;
          border: 0;
          outline: 0;
          border-bottom: 1px solid #dee0e3;
          line-height: 30px;
          &::placeholder {
            color: #bbbfc4;
          }
        }
        div {
          font-size: 12px;
          color: #8f959e;
        }
      }
      .select div {
        font-size: 12px;
        color: #8f959e;
        margin-bottom: 6px;
      }
      .remember {
        padding-bottom: 20px;
      }
      /deep/ .el-button {
        width: 100%;
      }
      /deep/ .el-select {
        width: 100%;
        padding-bottom: 6px;
      }
    }
  }
}
</style>
